import sys
from typing import Dict

# 解析命令	一键发送重量
# 0X20

def parse_scale_data(data: bytes) -> Dict:
    """解析电子秤数据协议"""
    if len(data) != 15:
        raise ValueError("数据长度必须为15字节")

    # 校验包头包尾
    if data[0] != 0xAA or data[-1] != 0x2F:
        raise ValueError("无效的包头或包尾")
    
    """计算称重数据包校验码计算验证码"""
    # 范围：第1字节（包头）到第13字节（皮重结束）
    checksum_bytes = data[0:13]
    checksum =sum(checksum_bytes) % 256

    # # 验证校验码
    if checksum != data[-2]:
        raise ValueError(f"验证码错误，计算值0x{checksum:02X}，接收值0x{data[-2]:02X}")

    # 解析字段
    length = data[1]
    command = data[2]
    
    # 解析符号和单位
    sign_unit = data[3]
    if sign_unit == 0x81:
        sign, unit = "+", "KG"
    elif sign_unit == 0x01:
        sign, unit = "-", "KG"
    else:
        sign, unit = "", "UNKNOWN"
    
    # 解析数值
    decimal_places = data[4]
    net_weight = int.from_bytes(data[5:9], "big")
    stability = "稳定" if data[9] == 0x0A else "不稳定"
    tare = int.from_bytes(data[10:13], "big")

    # 应用小数位
    net_weight = (-1 if sign == "-" else 1) * net_weight / (10**decimal_places)
    tare = tare / (10**decimal_places)

    return {
        "包头": "0xAA",
        "长度": length,
        "命令": f"0x{command:02X}",
        "符号": sign,
        "单位": unit,
        "小数位": decimal_places,
        "净重": f"{net_weight:.{decimal_places}f} {unit}",
        "稳定状态": stability,
        "皮重": f"{tare:.{decimal_places}f} {unit}",
        "验证码": f"0x{data[-2]:02X}",
        "包尾": "0x2F"
    }

if __name__ == "__main__":
    # 测试数据：AA 0B 20 01 03 00 00 00 28 0A 00 00 00 0B 2F
    test_data = bytes.fromhex("AA 0B 20 81 03 00 00 00 8C 0A 00 00 00 EF 2F  ")

    try:
        result = parse_scale_data(test_data)
        for k, v in result.items():
            print(f"{k:<8}: {v}")
    except Exception as e:
        print(f"解析失败: {str(e)}")
        sys.exit(1)